#include <QMetaObject>
#include <QMetaProperty>
//#include <QDebug>
#include <QDir>
#include <QtWidgets>
#include <QSet>
#include <QQueue>
#include <QScreen>
#include <QCursor>

#include "display/SwitchButton.h"
#include "ConfigEditor.h"
#include "ConfigSearchBar.h"
#include "ConfigData.h"


ConfigEditor::ConfigEditor(QWidget *parent) : QWidget(parent)
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setMargin(25);
    QHBoxLayout *headLine = new QHBoxLayout;
    headLine->addStretch();
    switchButton = new SwitchButton;
    headLine->addWidget(switchButton);
    headLine->addStretch();
    resetButton = new QPushButton(tr("Reset"));
    headLine->addWidget(resetButton);
    mainLayout->addLayout(headLine);
    mainLayout->addSpacing(20);

    QHBoxLayout *layout = new QHBoxLayout;
    auto searchLable = new QLabel(tr("Search"));
    searchBar = new ConfigSearchBar(&ConfigData::instance(), this);
    //searchBar->setMaximumWidth(200);
    layout->addStretch();
    layout->addWidget(searchLable);
    layout->addSpacing(10);
    layout->addWidget(searchBar);
    layout->addStretch();

    mainLayout->addLayout(layout);
    mainLayout->addSpacing(20);

    scrollWidget = new QScrollArea(this);
    scrollWidget->setFrameShape(QFrame::NoFrame);
    scrollWidget->setContentsMargins(10, 10, 10, 10);
    scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollWidget->setWidgetResizable(true);
    scrollWidget->setMinimumWidth(500);
    scrollWidget->verticalScrollBar()->setProperty("_d_dtk_slider_always_show", true);
    mainLayout->addWidget(scrollWidget);

    mainLayout->addSpacing(20);

    this->setLayout(mainLayout);


    QQueue<ConfigDataModel*> models;
    models.enqueue(&ConfigData::instance());

    while (!models.isEmpty())
    {
        ConfigDataModel *model = models.dequeue();
        const QMetaObject *obj = model->metaObject();
        QWidget *w = new QWidget; // leak
        QHBoxLayout *hlayout = new QHBoxLayout;
        QFormLayout *formLayout = new QFormLayout;
        formLayout->setVerticalSpacing(20);
        formLayout->setHorizontalSpacing(40);
        hlayout->addStretch(1);
        hlayout->addLayout(formLayout, 5);
        hlayout->addStretch(1);
        w->setLayout(hlayout);
        w->adjustSize();
        w->setMinimumWidth(400);
        subWidgets.append(w);
        switchButton->append(model->translatedName);
        for (int i = obj->propertyOffset(); i < obj->propertyCount(); i++)
        {
            QMetaProperty property = obj->property(i);
            if (property.read(model).canConvert<ConfigItem*>())
            {
                ConfigItem *item = property.read(model).value<ConfigItem*>();
                QWidget *content = item->createRelatedWidget();
                if (content != nullptr)
                {
                    QLabel *label = new QLabel(item->translatedName);
                    label->setMinimumSize(label->sizeHint());
                    formLayout->addRow(label, content);
                }
            }
            else if (property.read(model).canConvert<ConfigDataModel*>())
            {
                models.enqueue(property.read(model).value<ConfigDataModel*>());
            }
        }
    }

    connect(switchButton, &SwitchButton::indexChanged, this, &ConfigEditor::onSwitchButtonIndexChanged);
    connect(resetButton, &QPushButton::clicked, this, &ConfigEditor::onResetButtonClicked);

    subWidgets.squeeze();
    // subWidgets[1]->setEnabled(false);
    switchButton->setFocus();
    switchButton->setCurrentIndex(0);
    setWindowTitle(tr("TranslateStar Config"));

    resize(sizeHint());

    for (auto screen : QGuiApplication::screens())
    {
        if (screen->availableGeometry().contains(QCursor::pos()))
        {
            QRect screenRect = screen->availableGeometry();
            move(screenRect.topLeft() + QPoint(screenRect.width() - width(), screenRect.height() - height()) / 2);
            break;
        }
    }

}

ConfigEditor::~ConfigEditor()
{
    for (auto w : subWidgets)
    {
        w->deleteLater();
    }
}


void ConfigEditor::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(QPen(QColor(200, 200, 200), 2));
    QRect frame = scrollWidget->rect();
    frame.moveTo(scrollWidget->pos());
    frame.adjust(-5, -5, 5, 5);
    painter.drawRoundedRect(frame, 10, 10);
    QWidget::paintEvent(event);
}

void ConfigEditor::closeEvent(QCloseEvent *event)
{
    emit aboutToClose();
    (&ConfigData::instance())->writeToFile();
    QWidget::closeEvent(event);
}


void ConfigEditor::onResetButtonClicked()
{
    (&ConfigData::instance())->resetAll();
}

void ConfigEditor::onSwitchButtonIndexChanged(int index)
{
    scrollWidget->takeWidget();
    scrollWidget->setWidget(subWidgets.at(index));
}

